#
# Copyright (C) 2023, Inria
# GRAPHDECO research group, https://team.inria.fr/graphdeco
# All rights reserved.
#
# This software is free for non-commercial, research and evaluation use
# under the terms of the LICENSE.md file.
#
# For inquiries contact  george.drettakis@inria.fr
#

from typing import List, Tuple, Dict, Any

import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import Tensor
from plyfile import PlyElement
import numpy as np
from numpy import ndarray
from simple_knn._C import distCUDA2

from modules.data import BasicPointCloud
from modules.model import GaussianModel_SH
from modules.utils.sh_utils import RGB2SH
from modules.utils.modeling_utils import *
from modules.utils.training_utils import *

from .hparam import HyperParams


class GaussianModel(GaussianModel_SH):

    ''' carve-gs '''

    def __init__(self, hp):
        super().__init__(hp)
    
        self.hp: HyperParams

        # stats
        self.age: Tensor = None
        # original pcd
        self.pcd_points: ndarray = None
        self.pcd_colors: ndarray = None

    def state_dict(self) -> Dict[str, Any]:
        state_dict = super().state_dict()
        state_dict.update({
            'age': self.age,
        })
        return state_dict

    def load_state_dict(self, state_dict:Dict[str, Any]):
        self.age = state_dict['age']
        super().load_state_dict(state_dict)

    def resample_pcd(self, why:str) -> Dict[str, Tensor]:
        # resample pcd points
        n_pts_all = len(self.pcd_points)
        sel = np.random.uniform(size=[n_pts_all]) < self.hp.resample_ratio
        points = self.pcd_points[sel]
        colors = self.pcd_colors[sel]
        n_sel = len(points)
        if why == 'init':
            n_sel = max(n_sel, self.hp.resample_init_count_min)
            n_sel = min(n_sel, self.hp.resample_init_count_max)
        elif why == 'incr':
            n_sel = max(n_sel, self.hp.resample_incr_count_min)
            n_sel = min(n_sel, self.hp.resample_incr_count_max)
        else:
            raise ValueError(f'>> unknown reason: {why}')
        if len(points) > n_sel:
            points = points[:n_sel]
            colors = colors[:n_sel]

        # convert to props
        points = torch.from_numpy(points).to(dtype=torch.float, device='cuda')
        colors = torch.from_numpy(colors).to(dtype=torch.float, device='cuda')
        n_pts = points.shape[0]
        print(f'Number of points {why}:', n_pts)

        dists = torch.clamp_min(distCUDA2(points), 0.0000001)
        scales = torch.log(torch.sqrt(dists))[...,None].repeat(1, 3)
        rots = torch.zeros((n_pts, 4), device='cuda')
        rots[:, 0] = 1
        features = torch.zeros((n_pts, 3, (self.max_sh_degree + 1) ** 2), dtype=torch.float, device='cuda')
        features[:, :3, 0 ] = RGB2SH(colors)  # dc
        features[:, 3:, 1:] = 0.0             # rest
        opacities = inverse_sigmoid(0.1 * torch.ones((n_pts, 1), dtype=torch.float, device='cuda'))

        return {
            'xyz':     nn.Parameter(points, requires_grad=True), 
            'scale':   nn.Parameter(scales, requires_grad=True), 
            'rot':     nn.Parameter(rots  , requires_grad=True), 
            'f_dc':    nn.Parameter(features[:, :, 0:1].transpose(1, 2).contiguous(), requires_grad=True), 
            'f_rest':  nn.Parameter(features[:, :, 1: ].transpose(1, 2).contiguous(), requires_grad=True), 
            'opacity': nn.Parameter(opacities, requires_grad=True), 
        }

    def from_pcd(self, pcd:BasicPointCloud):
        print('Number of points in pool:', len(pcd.points))
        self.pcd_points = np.asarray(pcd.points)
        self.pcd_colors = np.asarray(pcd.colors)

        props = self.resample_pcd('init')
        self._xyz           = props['xyz']
        self._scaling       = props['scale']
        self._rotation      = props['rot']
        self._features_dc   = props['f_dc']
        self._features_rest = props['f_rest']
        self._opacity       = props['opacity']

        n_pts = len(self._xyz)
        self.age = torch.zeros((n_pts, 1), device='cuda')

    def load_ply(self, elem:PlyElement):
        super().load_ply(elem)

        n_pts = len(elem['x'])
        age = np.zeros([n_pts, 1], dtype=np.int32)
        self.age = torch.tensor(age, dtype=torch.int, device='cuda')

    def save_ply(self) -> Tuple[List[ndarray], List[str]]:
        property_data, property_names = super().save_ply()
        property_data.extend([
            self.age.cpu().numpy(),
        ])
        property_names.extend([
            'age'
        ])
        return property_data, property_names

    def prune_points(self, mask:Tensor):
        super().prune_points(mask)
        valid_points_mask = ~mask
        self.age = self.age[valid_points_mask]

    def densification_postfix(self, new_xyz:Tensor, new_scaling:Tensor, new_rotation:Tensor, new_features_dc:Tensor, new_features_rest:Tensor, new_opacities:Tensor, selected_pts_mask:Tensor=None):
        super().densification_postfix(new_xyz, new_scaling, new_rotation, new_features_dc, new_features_rest, new_opacities)
        if selected_pts_mask is None:   # newly resampled from pcd, turn to the new Aeon!
            self.age += 1
            self.age = F.pad(self.age, (0, 0, 0, len(new_xyz)))
        else:                           # split/clone from the old
            self.age = torch.cat([self.age, self.age[selected_pts_mask] + 1])

    def densify_and_clone(self, grads:Tensor, grad_threshold:float, scene_extent:float):
        # Extract points that satisfy the gradient condition
        selected_pts_mask = torch.where(torch.norm(grads, dim=-1) >= grad_threshold, True, False)
        selected_pts_mask = torch.logical_and(selected_pts_mask, torch.max(self.scaling, dim=1).values <= self.percent_dense*scene_extent)

        new_xyz           = self._xyz          [selected_pts_mask]
        new_scaling       = self._scaling      [selected_pts_mask]
        new_rotation      = self._rotation     [selected_pts_mask]
        new_features_dc   = self._features_dc  [selected_pts_mask]
        new_features_rest = self._features_rest[selected_pts_mask]
        new_opacities     = self._opacity      [selected_pts_mask]

        # NOTE: 多传一个参数 selected_pts_mask
        self.densification_postfix(new_xyz, new_scaling, new_rotation, new_features_dc, new_features_rest, new_opacities, selected_pts_mask)

    def densify_and_resample(self):
        props = self.resample_pcd('incr')
        new_xyz           = props['xyz']
        new_scaling       = props['scale']
        new_rotation      = props['rot']
        new_features_dc   = props['f_dc']
        new_features_rest = props['f_rest']
        new_opacities     = props['opacity']

        # NOTE: 多传一个参数 selected_pts_mask
        self.densification_postfix(new_xyz, new_scaling, new_rotation, new_features_dc, new_features_rest, new_opacities, selected_pts_mask=None)

    def densify_and_split(self, grads:Tensor, grad_threshold:float, scene_extent:float, N:int=2):
        # this is replaced by .densify_and_resample()
        pass
